﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Noesis.Javascript;
namespace TemplateEngine
{
    internal class V8Template : ITemplate
    {
        private String _script;
        private String _returnKey;
        public V8Template(String script, String returnKey)
        {
            _script = script;
            _returnKey = returnKey;
        }

        private static readonly Object StaticSyncLock = new object();
        private static readonly JavascriptContext jc = new JavascriptContext();

        public string Process(System.Collections.IDictionary data)
        {
            lock (StaticSyncLock)
            {
                if (data != null)
                {
                    foreach (Object key in data.Keys)
                    {
                        if (key != null)
                        {
                            jc.SetParameter(key.ToString(), data[key]);
                        }
                    }
                }
                jc.Run(_script);
                Object rv = jc.GetParameter(_returnKey);
                return rv != null ? rv.ToString() : null;
            }
        }
    }
}
